import logging

import requests
from requests import Response

logger = logging.getLogger(__name__)


class RequestUtil:
    _session = requests.Session()

    @staticmethod
    def send_request(**kwargs) -> Response:
        """
        通过 Session 发送请求
        :param kwargs: 参数
        :return: 返回 response
        """
        # 循环遍历参数，并将参数写入日志
        for args_key, args_value in kwargs.items():
            # 写入请求参数日志
            logger.info("请求" + args_key + "参数：%s" % args_value)
            if args_key == "files":
                for key, value in args_value.items():
                    args_value[key] = open(value, "rb")
        # 发送请求
        response = RequestUtil._session.request(**kwargs)
        # 如果响应报文为 json 格式，则写入 log
        if "json" in response.headers.get("Content-Type"):
            logger.info("响应正文：%s" % response.json())
        else:
            # 如果为 html 则不写入 Log
            logger.info("响应正文：太长暂不显示")

        return response
